package com.ideal.manage.esms.service.project;

import com.ideal.manage.esms.bean.DTO.DeployTree;
import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.DTO.ZtreeDto;
import com.ideal.manage.esms.bean.project.ArithmeticDeployManage;
import com.ideal.manage.esms.bean.project.ArithmeticManage;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.ProjectManage;
import com.ideal.manage.esms.bean.sys.User;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.project.ProjectManageRepository;
import com.ideal.manage.esms.repository.system.UserRepository;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created By Dai On 2018/4/24
 * Remark: 工程配置 -> 项目管理 Service
 */
@Service
public class ProjectManageService {
    @Autowired
    private ProjectManageRepository projectManageRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private EquipmentManageService equipmentManageService;

    @Autowired
    private ArithmeticManageService arithmeticManageService;

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 数据表
     *
     * @param pageNum
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<ProjectManage> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<ProjectManage> page = projectManageRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<ProjectManage> parameters = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(parameters);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 根据id 查找项目管理对象
     *
     * @return
     */
    public ProjectManage findOne(String id) {
        return projectManageRepository.findOne(id);
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 保存
     *
     * @param id
     * @param name
     * @param ip
     * @param uploadCycle
     */
    public String saveProject(String id, String name, String ip, Long uploadCycle) {
        ProjectManage old = projectManageRepository.findByName(name);
        ProjectManage projectManage = new ProjectManage();
        if (StringUtils.isNotBlank(id)) {
            if (!old.getId().equals(id)) {
                return "项目名不可重复";
            }
            projectManage = projectManageRepository.findOne(id);
        } else {
            if (old != null) {
                return "项目名不可重复";
            }
            //获取当前登录用户
            MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
            User user = userRepository.findOne(shiroUser.getId());
            projectManage.setCreateTime(new Date());
            projectManage.setCreateUser(user);
        }
        projectManage.setUpdateTime(new Date());
        projectManage.setName(name);
        projectManage.setIp(ip);
        projectManage.setUploadCycle(uploadCycle);
        projectManageRepository.save(projectManage);
        return "保存成功";
    }

    /**
     * 工程配置 -> 对象管理 -> 项目管理 -> 删除
     *
     * @param ids
     * @return
     */
    public void deleteProject(String[] ids) {
        List<ProjectManage> projectManages = projectManageRepository.findAll(Arrays.asList(ids));
        projectManages.forEach(projectManage -> projectManage.setIsValid(0));
        projectManageRepository.save(projectManages);
    }

    /**
     * 用id找到对应的项目并生成ZtreeDto
     *
     * @param id
     * @return
     */
    public List findZtreeDtoById(String id) {
        ProjectManage projectManage = projectManageRepository.findOne(id);
        List list = new ArrayList<ZtreeDto>() {{
            add(new ZtreeDto(projectManage.getId(), null, projectManage.getName(), "0"));
        }};
        return list;
    }

    /**
     * 找到所有的项目并生成DeployTree
     *
     * @return
     */
    public List findDeployTree() {
        int equipmentLength = 0;
        int allLength = 0;
        List<ArithmeticDeployManage> arithmeticDeployManages1 = arithmeticManageService.findAllDeployManages();
        allLength = arithmeticDeployManages1.size();
        List<ProjectManage> projectManages = projectManageRepository.findAllManages();
        List<DeployTree> list = new ArrayList<DeployTree>();
        for (ProjectManage projectManage : projectManages) {
            int arithmeticLength = 0;
            List<EquipmentManage> equipmentManages = equipmentManageService.findByProjectId(projectManage.getId());
            equipmentLength = equipmentManages.size();
            for (EquipmentManage equipmentManage : equipmentManages) {
                List<ArithmeticDeployManage> arithmeticDeployManages = arithmeticManageService.findByEquipmentId(equipmentManage.getId());
                arithmeticLength += arithmeticDeployManages.size();
            }
            if (arithmeticLength != 0 && (arithmeticLength == allLength * equipmentLength)) {
                list.add(new DeployTree(projectManage.getId(), null, projectManage.getName(), null, null, "true"));
            } else {
                list.add(new DeployTree(projectManage.getId(), null, projectManage.getName(), null, null, "false"));
            }
        }
        return list;
    }

    /**
     * 根绝id并生成DeployTree
     *
     * @return
     */
    public List<DeployTree> findDeployTree(String id) {
        int equipmentLength = 0;
        int arithmeticLength = 0;
        int allLength = 0;
        List<DeployTree> list = new ArrayList<>();
        List<ArithmeticManage> arithmeticManages = arithmeticManageService.findManages();
        allLength = arithmeticManages.size();//算法的长度
        ProjectManage projectManage = projectManageRepository.findOne(id);

        List<EquipmentManage> equipmentManages = equipmentManageService.findByProjectId(projectManage.getId());
        equipmentLength = equipmentManages.size();//设备的长度
        for (EquipmentManage equipmentManage : equipmentManages) {
            List<ArithmeticDeployManage> arithmeticDeployManages = arithmeticManageService.findByEquipmentId(equipmentManage.getId());
            arithmeticLength += arithmeticDeployManages.size();//所有设备的算法部署的长度
        }
        if (arithmeticLength != 0 && (arithmeticLength == allLength * equipmentLength)) {
            list.add(new DeployTree(projectManage.getId(), null, projectManage.getName(), null, null, "true"));
        } else {
            list.add(new DeployTree(projectManage.getId(), null, projectManage.getName(), null, null, "false"));
        }
        return list;
    }

    public List<ProjectManage> findAllManages(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<ProjectManage> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<ProjectManage> page = projectManageRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<ProjectManage> parameters = page.getContent();
        return parameters;
    }

    public ProjectManage findProjectManageByEquipmentId(String equipmentId) {
        ProjectManage projectManage = projectManageRepository.findByEquipmentId(equipmentId);
        return projectManage;
    }

    public List<ProjectManage> findAllProjects() {
        return projectManageRepository.findAllProjects();
    }

}
